package com.example.ymm.modules1.service.impl.hl.ex;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.dto.HengLiConstants;
import com.example.ymm.exception.YmException;
import com.example.ymm.model.CommonResult;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;

import com.example.ymm.modules1.entity.hl.ex.*;
import com.example.ymm.modules1.mapper.ex.ExUserAnserMapper;
import com.example.ymm.modules1.query.hl.ex.*;
import com.example.ymm.modules1.service.dto.heng.ex.*;
import com.example.ymm.modules1.service.hl.ex.*;
import com.example.ymm.util.QueryHelpPlus;
import com.example.ymm.util.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
//@DSTransactional
@Slf4j
@DS("slave2")
public class ExUserAnsererviceImpl extends BaseServiceImpl<ExUserAnserMapper, ExUserAnser> implements ExUserAnserService {
    @Autowired
    ExTeamRuleService exTeamRuleService;
    @Autowired
    ExPublishPaperService exPublishPaperService;
    @Autowired
    private ExPaperService exPaperService;

    @Autowired
    private ExUserGroupService exUserGroupService;
    @Autowired
    private ExPublishQuestionService exPublishQuestionService;

    @Autowired
    private ExUserPaperService exUserPaperService;
    @Autowired
    private ExUserOptionService exUserOptionService;

    @Override
    public TableList<ExUserAnser> list(ExUserAnserQueryCriteria criteria, YmPageDto pageDto) {
        IPage<ExUserAnser> page = new Page<ExUserAnser>(pageDto.getPage(),pageDto.getPageSize());
        QueryWrapper predicate = QueryHelpPlus.getPredicate(ExUserAnser.class, criteria);
        predicate.orderByDesc("create_time");
        baseMapper.selectPage(page, predicate);
        TableList<ExUserAnser> tableList=new TableList(page);
        return tableList;
    }

    public List<ExUserAnser> queryAll(ExUserAnserQueryCriteria criteria) {
        QueryWrapper predicate = QueryHelpPlus.getPredicate(ExUserAnser.class, criteria);
        predicate.orderByDesc("create_time");
        List<ExUserAnser> result =baseMapper.selectList(predicate);
        return result;
    }

    @Override
    public UserAnserDto getUserScore(ExUserAnserQueryCriteria criteria) {

        UserAnserDto userErroScore = baseMapper.getUserErroScore(criteria);
        UserAnserDto userTrueScore = baseMapper.getUserTrueScore(criteria);
        UserAnserDto userScore = null;
        userScore=new UserAnserDto();
        userScore.setUserName(criteria.getUserName());
        userScore.setResultScore(0);
        userScore.setTrueScore(0);
        userScore.setErroScore(0);
        if(UtilValidate.isNotEmpty(userTrueScore)){
            userScore.setTrueScore(userTrueScore.getTrueScore());
            userScore.setTrueNum(userTrueScore.getTrueNum());
            userScore.setQuestionNum(userTrueScore.getTrueNum());
        }
        if(UtilValidate.isNotEmpty(userErroScore)){
            userScore.setErroScore(userErroScore.getErroScore());
            userScore.setErroNum(userErroScore.getErroNum());
            if(UtilValidate.isNotEmpty(userScore.getQuestionNum())){
                Integer questionNum = userScore.getQuestionNum()+userErroScore.getErroNum();
                userScore.setQuestionNum(questionNum);
            }else{
                userScore.setQuestionNum(userErroScore.getErroNum());
            }
        }
        userScore.setResultScore((UtilValidate.isNotEmpty(userScore.getTrueScore())?userScore.getTrueScore():0)- (UtilValidate.isNotEmpty(userScore.getErroScore())?userScore.getErroScore():0));

        return userScore;
    }


    @Override
    public UserAnserDetailDto getUserScoreDetail(ExUserAnserQueryCriteria criteria) {

        UserAnserDetailDto userScore = null;
        userScore=new UserAnserDetailDto();


        UserAnserDto userScore1 = getUserScore(criteria);
        BeanUtils.copyProperties(userScore1,userScore);
        /**
         * 统计回答了的题目数量
         */
        LambdaQueryWrapper<ExUserAnser> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ExUserAnser::getUserName,userScore1.getUserName());
        queryWrapper.eq(ExUserAnser::getPublishPaperId,criteria.getPublishPaperId());
        queryWrapper.eq(ExUserAnser::getHaveAnser,1);
        long count = count(queryWrapper);
        userScore.setAnserNum((int) count);
        return userScore;
    }

    @Override
    public List<UserAnserView> getUserAnsers(ExUserAnserQueryCriteria criteria) {
        List<UserAnserView> userAnsers = baseMapper.getUserAnsers(criteria);
        List<UserOptionView> userOptions = getUserOptions(criteria);
        ExPublishOptionQueryCriteria c2=new ExPublishOptionQueryCriteria();
        c2.setPublishPaperId(criteria.getPublishPaperId());
        c2.setIzTrue("1");
//        c2.setPublishQuestionId(userAnser.getPublishQuestionId());
        List<PublishOptionView> all_trueOptions = baseMapper.getPublishOptions(c2);

        //查询原题中所有的选项
        ExPublishOptionQueryCriteria c3=new ExPublishOptionQueryCriteria();
        c3.setPublishPaperId(criteria.getPublishPaperId());
        List<PublishOptionView> all_Options = baseMapper.getPublishOptions(c3);
        for (UserAnserView userAnser : userAnsers) {
            //收集用户选项
            List<UserOptionView> options=new ArrayList<UserOptionView>();
            //收集正确选项
            List<PublishOptionView> trueOptions=new ArrayList<>();
            //收集原题中的所有选项
            List<PublishOptionView> allOptions=new ArrayList<>();
            List<String> titles=new ArrayList<>();
            for(PublishOptionView tOption : all_trueOptions){
                if(tOption.getPublishQuestionId().equals(userAnser.getPublishQuestionId())){
                    trueOptions.add(tOption);

                }
            }

            for (UserOptionView userOption : userOptions) {
                if(userOption.getPublishQuestionId().equals(userAnser.getPublishQuestionId())){
                    options.add(userOption);
                }
            }
            for(PublishOptionView tOption : all_Options){
                if(tOption.getPublishQuestionId().equals(userAnser.getPublishQuestionId())){
                    allOptions.add(tOption);
                    titles.add(tOption.getLetter()+":"+tOption.getTitle());
                }
            }
            if(UtilValidate.isEmpty(userAnser.getTitle())){
                userAnser.setTitle(String.join(" ", titles));
            }
            //原题中正确的选项
            userAnser.setTrueOptions(trueOptions);
            //用户选择的选项
            userAnser.setOptions(options);
            //原题中所有的选项
            userAnser.setAllOptions(allOptions);
        }
        return userAnsers;
    }


    @Override
    public List<UserOptionView> getUserOptions(ExUserAnserQueryCriteria criteria) {
        return baseMapper.getUserOptions(criteria);
    }


    @Override
    public List<ExUserAnser> getAnsersByQuestionId(ExQuestionQueryCriteria criteria) {
        return baseMapper.getAnsersByQuestionId(criteria);
    }

    @Override
    public List<ExPublishPaper> getAnsersPublishPaper(ExQuestionQueryCriteria criteria) {
        return baseMapper.getAnsersPublishPaper(criteria);
    }

    @Override
    public List<ExUserPaper> againCountQuestionScoreFn(ExQuestionQueryCriteria c1) {
        String[] idArr = c1.getPublishPaperId().split(",");
        List<ExUserPaper> result=new ArrayList<>();
        for (String publishPaperId : idArr) {
            c1.setPublishPaperId(publishPaperId);
            ExPublishPaper publishPaper = exPublishPaperService.getById(publishPaperId);
            List<ExUserAnser> exUserAnsers =getAnsersByQuestionId(c1);
            ExPublishOptionQueryCriteria criteria=new ExPublishOptionQueryCriteria();
            criteria.setPublishPaperId(publishPaperId);
            criteria.setQuestionId(c1.getQuestionId());

            List<PublishOptionView> all_Options = baseMapper.getPublishOptions(criteria);


            ExUserAnserQueryCriteria c3=new ExUserAnserQueryCriteria();
            c3.setPublishPaperId(publishPaperId);
            c3.setQuestionId(c1.getQuestionId());
            List<UserOptionView> userOptions = getUserOptions(c3);


            Map<String,String> teamRuleIdMap=new HashMap<>();
            Map<String,ExTeamRule> teamRuleDataMap=new HashMap<>();
            for (ExUserAnser exUserAnser : exUserAnsers) {
                if(UtilValidate.isNotEmpty(exUserAnser.getTeamRuleId())){
                    teamRuleIdMap.put(exUserAnser.getTeamRuleId(),exUserAnser.getTeamRuleId());
                }
            }
            List<ExTeamRule> exTeamRules=null;
            if(!teamRuleIdMap.isEmpty()){
                ExTeamRuleQueryCriteria cc1=new ExTeamRuleQueryCriteria();
                cc1.setIdIn(Arrays.asList(teamRuleIdMap.keySet().toArray(new String[0])));
                exTeamRules = exTeamRuleService.queryAll(cc1);
                if(UtilValidate.isNotEmpty(exTeamRules)){
                    for(ExTeamRule exTeamRule : exTeamRules){
                        teamRuleDataMap.put(exTeamRule.getId(),exTeamRule);
                    }
                }
            }



            for (ExUserAnser exUserAnser : exUserAnsers) {
                List<UserOptionView> userOption_arr=new ArrayList<>();
                //收集用户选项
                for (UserOptionView userOption : userOptions) {
                    if(userOption.getPublishQuestionId().equals(exUserAnser.getPublishQuestionId())){
                        userOption_arr.add(userOption);
                    }
                }


                int user_true_num=0;//你选了正确的选项数量
                int user_erro_num=0;//你选了错误的选项数量
                int question_true_num=0;//总共正确的选项数量
                boolean allTrue=false;
                //收集用户选项

                //对比正确选项
                for (PublishOptionView tOption : all_Options) {
                    if(tOption.getIsTrue().equals(1)){
                        question_true_num++;
                    }

                }
                for (PublishOptionView tOption : all_Options) {
                    for (UserOptionView userOption : userOption_arr) {
                        if(tOption.getOptionId().equals(userOption.getOptionId())){
                            if(tOption.getIsTrue().equals(1)){
                                user_true_num++;
                            }else{
                                user_erro_num++;
                            }
                        }
                    }

                }
                //判断这道题对不对
                if(question_true_num==user_true_num&&user_erro_num==0){
                    allTrue=true;
                }
                ExTeamRule teamRule=null;
                if(UtilValidate.isNotEmpty(exUserAnser.getTeamRuleId())){
                    if(teamRuleDataMap.containsKey(exUserAnser.getTeamRuleId())){
                         teamRule = teamRuleDataMap.get(exUserAnser.getTeamRuleId());
                    }
                }

                if(allTrue){
                    exUserAnser.setIsTrue(1);
                    if(UtilValidate.isNotEmpty(teamRule)&&UtilValidate.isNotEmpty(teamRule.getTrueScore())){
                        exUserAnser.setScore(teamRule.getTrueScore());
                    }else{
                        exUserAnser.setScore(0);
                    }
                }else{
                    exUserAnser.setIsTrue(0);
                    if(UtilValidate.isNotEmpty(teamRule)&&UtilValidate.isNotEmpty(teamRule.getErroScore())){
                        exUserAnser.setScore(teamRule.getErroScore());
                    }else{
                        exUserAnser.setScore(0);
                    }
                }

                saveOrUpdate(exUserAnser);
                //试卷重新计分
                ExUserAnserQueryCriteria c4=new ExUserAnserQueryCriteria();
                c4.setPublishPaperId(publishPaperId);
                c4.setUserPaperId(exUserAnser.getUserPaperId());
                UserAnserDto userScore = getUserScore(c4);
                ExUserPaper userPaper = exUserPaperService.getById(exUserAnser.getUserPaperId());
                if(UtilValidate.isNotEmpty(userPaper)){
                    userPaper.setScore(userScore.getResultScore());
                    exUserPaperService.saveOrUpdate(userPaper);
                    userPaper.setPaperName(publishPaper.getPaperName());
                    result.add(userPaper);
                }

            }


        }
        return result;
    }


    @Override
    public List<GroupOneResultDto> manageUserScoreByMainShi(String userPaperId) {
        List<GroupOneResultDto> list=new ArrayList<>();
        ExUserPaper exUserPaper = exUserPaperService.getById(userPaperId);

        ExUserGroupQueryCriteria c=new ExUserGroupQueryCriteria();
        c.setUserName(exUserPaper.getUserName());
        c.setUserPaperId(userPaperId);
        c.setPublishPaperId(exUserPaper.getPublishPaperId());

        List<ExUserGroup> exUserGroups = exUserGroupService.queryAll(c);
        for (int i = 0; i < exUserGroups.size(); i++) {
            ExUserGroup userGroup = exUserGroups.get(i);
            ExPublishQuestionQueryCriteria c2=new ExPublishQuestionQueryCriteria();
            c2.setPublishPaperId(userGroup.getPublishPaperId());
            c2.setPublishGroupId(userGroup.getPublishGroupId());
            ExPublishQuestion publishQuestion = exPublishQuestionService.queryOne(c2);

            String questionType="";
            GroupOneResultDto groupOneResultDto=new GroupOneResultDto();
            groupOneResultDto.setPublishGroupId(userGroup.getPublishGroupId());
            if(publishQuestion.getType().equals(HengLiConstants.xing_ge_question)){
                questionType="性格测试题";
                ExUserAnserQueryCriteria c3=new ExUserAnserQueryCriteria();
                c3.setUserName(exUserPaper.getUserName());
                c3.setPublishPaperId(userGroup.getPublishPaperId());
                c3.setPublishGroupId(userGroup.getPublishGroupId());
                UserXingGeAnserDto xingGeAnserDto = xinGeCountLetterGroup(c3);
                groupOneResultDto.setResult2(xingGeAnserDto);
            }else{
                questionType="选择题";
                ExUserAnserQueryCriteria c4=new ExUserAnserQueryCriteria();
                c4.setUserName(exUserPaper.getUserName());
                c4.setPublishPaperId(userGroup.getPublishPaperId());
                c4.setPublishGroupId(userGroup.getPublishGroupId());
                UserAnserDto userScore = getUserScore(c4);
                groupOneResultDto.setResult1(userScore);
            }
            groupOneResultDto.setGroupName(userGroup.getGroupName());
            groupOneResultDto.setQuestionType(questionType);
            groupOneResultDto.setSubmit(true);
            list.add(groupOneResultDto);
        }
        return list;
    }

    /**
     * 获取用户考试结果-面试卷
     * @param publishPaperId
     * @return
     */
    @Override
    public List<GroupOneResultDto> getUserScoreByMainShi(String publishPaperId) {


        String userName = getUserName();
        ExUserPaperQueryCriteria cc=new ExUserPaperQueryCriteria();
        cc.setPublishPaperId(publishPaperId);
        cc.setUserName(userName);
        String userPaperId=null;
        List<ExUserPaper> exUserPapers = exUserPaperService.queryAll(cc);
        if(UtilValidate.isNotEmpty(exUserPapers)){
            userPaperId=exUserPapers.get(0).getUserPaperId();
        }

        return manageUserScoreByMainShi(userPaperId);
    }




    @Override
    public UserXingGeAnserDto xinGeCountLetterGroup(ExUserAnserQueryCriteria criteria) {
        UserXingGeAnserDto xingGeAnserDto=new UserXingGeAnserDto();
        List<UserCountLetterListDto> letterListDtos = xinGeCountLetterList(criteria);
        if(UtilValidate.isEmpty(letterListDtos)){
            xingGeAnserDto.setAnserNum(0);
            xingGeAnserDto.setS(0);
            xingGeAnserDto.setP(0);
            xingGeAnserDto.setC(0);
            xingGeAnserDto.setM(0);
            return xingGeAnserDto;
        }

        xingGeAnserDto.setUserName(criteria.getUserName());
        String userId = getUserId();
        xingGeAnserDto.setUserId(userId);
        if(UtilValidate.isNotEmpty(letterListDtos)){
            Integer totalNum=0;
            for(UserCountLetterListDto letterListDto:letterListDtos){
                Integer num = letterListDto.getNum();
                if(UtilValidate.isNotEmpty(num)){
                    totalNum=totalNum+num;
                }
                switch (letterListDto.getLetter()){
                    case "C":
                        xingGeAnserDto.setC(num);

                        break;
                    case "S":
                        xingGeAnserDto.setS(num);
                        break;
                    case "M":
                        xingGeAnserDto.setM(num);
                        break;
                    case "P":
                        xingGeAnserDto.setP(num);
                        break;
                }
            }
            xingGeAnserDto.setAnserNum(totalNum);
        }

        return xingGeAnserDto;
    }

    @Override
    public List<UserCountLetterListDto> xinGeCountLetterList(ExUserAnserQueryCriteria criteria) {
        return baseMapper.xinGeCountLetterList(criteria);
    }

    @Override
    public GroupOneResultDto userSubQuestions(ExPublishPaper publishPaper,String userName) {

        if(UtilValidate.isEmpty(userName)){
            userName = getUserName();
        }

        ExPublishPaper samplePaper = exPublishPaperService.getSamplePaper(publishPaper.getPublishPaperId());
        ExPaper paper = exPaperService.getById(samplePaper.getPaperId());
        if(UtilValidate.isEmpty(paper)){
            throw new YmException("查找不到试卷信息!");
        }
        Integer ruleType = paper.getRuleType();
        ExPublishGroup startGroup = publishPaper.getStartGroup();


        ExUserAnserQueryCriteria criteria=new ExUserAnserQueryCriteria();
        criteria.setUserName(userName);
        criteria.setPublishPaperId(startGroup.getPublishPaperId());
        criteria.setPublishGroupId(startGroup.getPublishGroupId());
        List<ExUserAnser> exUserAnsers = queryAll(criteria);
        if(UtilValidate.isNotEmpty(exUserAnsers)){
           // throw new YmException("你已经提交过该模块的题目!");
            //删除这个模块的考试 答题 记录
            /**
             * ex_user_anser
             * ex_user_option
             */
            if(startGroup.getIzAgain()!=null&&startGroup.getIzAgain()==1){

                /**
                 * 判断是否全部没有答题
                 */
//                int have_anser=0;
//                List<ExPublishQuestion> questions = startGroup.getQuestions();
//                for (ExPublishQuestion question : questions) {
//                    List<ExPublishOption> options = question.getOptions();
//                    for (ExPublishOption option : options) {
//                        if(UtilValidate.isNotEmpty(option.getCheck())&&option.getCheck()){
//                            have_anser=1;
//                        }
//                    }
//                }
//
//                if(have_anser==1){
//
//                }else{
//
//                }
                LambdaQueryWrapper<ExUserAnser> lambdaQuery1=new LambdaQueryWrapper<>();
                lambdaQuery1.eq(ExUserAnser::getPublishGroupId,startGroup.getPublishPaperId());
                remove(lambdaQuery1);

                LambdaQueryWrapper<ExUserOption> lambdaQuery2=new LambdaQueryWrapper<>();
                lambdaQuery2.eq(ExUserOption::getPublishPaperId,startGroup.getPublishPaperId());
                exUserOptionService.remove(lambdaQuery2);
            }else{
                //throw new YmException("你已经提交过该模块的题目!");
                log.info("你已经提交过该模块的题目!");
                return null;
            }


        }

        GroupOneResultDto groupOneResultDto = new GroupOneResultDto();
        groupOneResultDto.setSubmit(true);
        //计分规则：1 区分团队 0 普通计分
        if(ruleType==1){
            UserAnserDto  userAnserDto = exPublishPaperService.sysSubmitPaper(publishPaper, userName);
            groupOneResultDto.setQuestionType("选择题");
            if(userAnserDto.isPaperOver()){
                groupOneResultDto.setPaperOver(true);
            }
            groupOneResultDto.setResult1(userAnserDto);
        }else{
            log.info("---面试交卷");
            //面试交卷
            GroupOneResultDto oneResultDto = exPublishPaperService.userSubmitPaper(publishPaper, userName);
            String questionType = oneResultDto.getQuestionType();
            if("选择题".equals(questionType)){
                groupOneResultDto.setResult1(oneResultDto.getResult1());
            }else{
                groupOneResultDto.setResult2(oneResultDto.getResult2());
            }
            if(oneResultDto.isPaperOver()){
                groupOneResultDto.setPaperOver(true);
            }
            groupOneResultDto.setQuestionType(questionType);
        }
        groupOneResultDto.setRuleType(ruleType);
        return groupOneResultDto;
    }
}
